<template>
  <s-layout
    title="个人主页"
    navbar="inner"
    :bgStyle="{
      ...state.style.background,
    }"
    :color="state.color"
    :navbarStyle="{ type: 'color', color: state.bgColor }"
  >
    <view class="user-info ss-flex">
      <image
        class="user-info-avatar"
        :src="sheep.$url.cdn(state.userInfo.avatar)"
        mode="aspectFill"
      ></image>
      <view class="user-info-text ss-flex flex-column justify-between align-start">
        <view class="user-info-name ss-flex align-center">
          <view class="name ss-line-1">{{ state.userInfo.nickname }}</view>
          <image
            class="gender"
            src="https://liuliangbenben.oss-cn-hangzhou.aliyuncs.com/mengchong/archives-woman.png"
            v-if="state.data.gender === 0"
          ></image>
          <image
            class="gender"
            src="https://liuliangbenben.oss-cn-hangzhou.aliyuncs.com/mengchong/archives-man.png"
            v-if="state.data.gender === 1"
          ></image>
        </view>
        <view
          class="data-right-my ss-flex justify-end"
          v-if="state.data.oneself === 1"
        >
          <view
            class="edit-user"
            @click="edit"
          >编辑资料</view>
        </view>
      </view>
    </view>
    <view class="synopsis">{{ state.data.bio || '这个人很懒没写什么简介' }}</view>

    <view class="data-box ss-flex justify-between align-end">
      <view class="data-left ss-flex">
        <view
          class="data-left-item ss-flex flex-column justify-center align-center"
          @click="jumpDetails('follow')"
        >
          <view class="num ss-line-1">{{ formatCharCount(state.data.followCount) || 0 }}</view>
          <view class="text">关注</view>
        </view>
        <view
          class="data-left-item ss-flex flex-column justify-center align-center"
          @click="jumpDetails('fans')"
        >
          <view class="num ss-line-1">{{ formatCharCount(state.data.fansCount) || 0 }}</view>
          <view class="text">粉丝</view>
        </view>
        <view
          class="data-left-item ss-flex flex-column justify-center align-center"
          @click="openModal"
        >
          <view class="num ss-line-1">{{ formatCharCount(state.data.zanCount) || 0 }}</view>
          <view class="text">获赞</view>
        </view>
        <view
          class="data-left-item ss-flex flex-column justify-center align-center"
          @click="collectCountClick"
        >
          <view class="num ss-line-1">{{ formatCharCount(state.data.collectCount) || 0 }}</view>
          <view class="text">收藏</view>
        </view>
      </view>
      <view class="data-right">
        <view class="data-right-other ss-flex justify-end">
          <view
            class="data-right-other-care"
            :class="[state.data.care === 1 ? 'is-care' : '']"
            @click="follow"
            v-if="state.data.oneself === 0"
          >{{ state.data.care === 1 ? '已关注' : '关注' }}</view>
          <view
            class="data-right-other-chat ss-flex justify-center align-center"
            @click="chat"
			v-if="state.data.oneself === 0"
          >
            <image
              src="https://liuliangbenben.oss-cn-hangzhou.aliyuncs.com/mengchong/message-bg.png"
              mode=""
            ></image>
            <view>私聊</view>
          </view>
        </view>
      </view>
    </view>

    <view class="tabs-box ss-flex justify-between align-center">
      <view
        class="tabs-item"
        :class="[state.tabStyle === 'publish' ? 'tab-active' : '']"
        @click="changeTab('publish')"
      >发布</view>
      <view
        class="tabs-item"
        :class="[state.tabStyle === 'collect' ? 'tab-active' : '']"
        @click="changeTab('collect')"
      >收藏</view>
      <view
        class="tabs-item"
        :class="[state.tabStyle === 'zan' ? 'tab-active' : '']"
        @click="changeTab('zan')"
      >点赞</view>
    </view>
    <!-- <view class="category-box ss-flex justify-start align-center">
      <view
        class="category-item"
        :class="[state.category_id === item.id ? 'category-active' : '']"
        @click="changeCategory(item.id)"
        v-for="(item, index) in state.category"
        :key="index"
        >{{ item.name }}</view
      >
    </view> -->
    <view
      class="list-box ss-flex ss-flex-wrap ss-row-between ss-p-x-26"
      v-if="state.list.length"
    >
      <assFindCard
        :findData="find"
        v-for="find in state.list"
        :key="find.find_id"
        @like="setLike(find)"
        @cardTap="jumpType(find, index)"
        :pinnedShow="true"
      >
      </assFindCard>
    </view>

    <!-- 获赞弹框 -->
    <CustomModal
      :visible="isModalVisible"
      :content="modalContent"
      :number="formatCharCount(state.data.zanCount)"
      @confirm="handleConfirm"
    />

    <uni-load-more
      v-if="state.total > 0"
      :status="state.loadStatus"
      :content-text="{
        contentdown: '上拉加载更多',
      }"
      @tap="loadmore"
    />
    <s-empty
      v-if="state.total <= 0 && state.loadStatus === 'noMore'"
      paddingTop="100"
      icon="https://liuliangbenben.oss-cn-hangzhou.aliyuncs.com/vocal/data-empty.png"
      text="暂无记录"
    ></s-empty>
    <view class="ss-safe-bottom"></view>
  </s-layout>
</template>

<script setup>
import sheep from '@/sheep';
import { ref, computed, reactive } from 'vue';
import { onLoad, onUnload, onReachBottom, onPageScroll, onShow } from '@dcloudio/uni-app';
import assApi from '@/association/api';
import API from '@/association/api';
import assFindCard from '@/components/ass-find-card';
import CustomModal from './CustomModal';
import association from '@/association/store';
import { formatCharCount } from '@/association/utils';
// const userInfo = computed(() => sheep.$store('user').userInfo);
// #ifdef APP
import imStore from "@/im/store/im.js"
// #endif
const template = computed(() => sheep.$store('app').template?.home);
const emit = defineEmits(['close']);
const state = reactive({
  current: 0,
  style: {
    background: {
      color: '#F5F5F5',
      src: 'https://liuliangbenben.oss-cn-hangzhou.aliyuncs.com/mengchong/user-bg.png',
    },
  },
  color: '#FFFFFF',
  user_id: '',
  data: {},
  page: 1,
  category: [],
  category_id: '',
  tabStyle: 'publish',
  list: [],
  total: 1,
  loadStatus: '',
  bgColor: 'transparent',
  // 是否初始化标识
  onceShow: false,
  userInfo: {
    avatar: '',
    nickname: ''
  }
});

const isModalVisible = ref(false); // 控制弹框是否显示
const modalContent = ref(`您已获得了${state.data?.zanCount}个赞`); // 弹框内容

// 点击收藏
const collectCountClick = () => {
  state.tabStyle = 'collect';
  changeTab('collect')
}
// 打开弹框
const openModal = () => {
  // state.data.oneself 1 表示自己，0 表示他人, 自己可以查看自己的获赞
  if (state.data.oneself === 1) {
    isModalVisible.value = true;
  }
};

// 关闭弹框
const closeModal = () => {
  isModalVisible.value = false;
};

// 处理确认按钮点击事件
const handleConfirm = () => {
  console.log('用户点击了确认');
  closeModal(); // 关闭弹框
};


onLoad((options) => {
  console.log('options: ', options);
  if (options) {
    state.user_id = options.id;
    getData();
    getCategory();
  }
  uni.$on('setInfo', (obj) => {
    state.data.nickname = obj.nickname;
    state.data.bio = obj.bio;
    state.data.gender = obj.gender;
    state.data.avatar = obj.avatar;
  });

});
onShow(() => {
  if (!state.onceShow) {
    state.onceShow = true;
    return;
  } else {
    changeTab(state.tabStyle);
  }
});

onUnload(() => {
  uni.$off('setInfo');
});

onReachBottom(() => {
  loadmore();
});

onPageScroll((e) => {
  const { scrollTop } = e;

  if (scrollTop > 0) {
    state.bgColor = '#fff';
    state.color = '#333333';
  } else {
    state.color = '#fff';
    state.bgColor = 'transparent';
  }
});

const loadmore = () => {
  if (state.loadStatus !== 'noMore') {
    state.page++;
    getList();
  }
};

// 切换发现喜欢状态
async function setLike (item) {
  let res = await API.findLike({
    find_id: item.find_id,
  });
  item.is_likes = !!res.data.is_like;
  if (item.is_likes) {
    item.likes += 1;
  } else {
    item.likes -= 1;
  }
}

const jumpType = (item, index) => {
  //   let platform = import.meta.env.SHOPRO_UDID_NAME;
  // sheep.$router.go('/association/pages/find', { id: item.find_id, type: item.label });

  //   if (item.label === 'visit_' + platform || item.label === 'share_' + platform) {

  //     if (item.file_type === 'video') {
  //       // // 跳转视频
  //       sheep.$router.go('/association/pages/asvideos', {
  //         id: item.find_id,
  //         index: index,
  //         category_id: state.findCategory,
  //       });
  //     } else {
  //       sheep.$router.go('/association/pages/find', { id: item.find_id, type: item.label });
  //     }
  //   }

  if (item.file_type === 'video') {
    // // 跳转视频
    sheep.$router.go('/association/pages/asvideos', {
      id: item.find_id,
      index: index,
      category_id: '',
      access_type: 'userCenter',
      user_id: state.user_id,
      style: state.tabStyle,
      tabShow: true
    });
  } else {
    sheep.$router.go('/association/pages/find', {
      id: item.find_id,
      type: item.label,
      user_id: state.user_id,
    });
  }

  //   if (item.label === 'questions_' + platform) {
  //     sheep.$router.go('/association/pages/find', { id: item.find_id, type: item.label });
  //   }
};

// 大分类
const changeTab = (type) => {
  state.tabStyle = type;
  state.page = 1;
  state.list = [];
  state.total = 1;
  getList();
};

// 子分类
const changeCategory = (id) => {
  state.category_id = id;
  state.page = 1;
  state.list = [];
  state.total = 1;
  getList();
};

const edit = () => {
  sheep.$router.go('/pages/user/info');
};

// 聊天
const chat = () => {
  let to = {
    aim: 'unfamMessage',
    // service.mobile 必传
    service: {
      mobile: state.data.mobile,
    },
  };
  const jsonParm = encodeURIComponent(JSON.stringify(to))
  // #ifdef APP
  	  imStore().webQueryAnalysis(to)
	  emit('close');
  	  // #endif
  // #ifndef APP
  uni.navigateTo({
    url: '/im/pages/web?to=' + jsonParm,
    success () {
      emit('close');
    },
  });
  // #endif
};

// 关注/取消关注
const follow = async () => {
  const { code, data } = await assApi.user.follow({
    user_id: state.user_id,
  });

  if (code === 1) {
    state.data.care = state.data.care === 1 ? 0 : 1;
    getData();
  }
};

// 关注 和 粉丝
const jumpDetails = (type) => {
  // state.data.oneself 1 表示自己，0 表示他人, 自己可以查看自己的关注列表以及粉丝列表
  if (state.data.oneself === 1) {
    if (type === 'follow') { // 跳转关注页面
      sheep.$router.go('/pages/user/userCenter/follow', {
        mobile: state.data.mobile,
      });
    } else {
      sheep.$router.go('/pages/user/userCenter/fans', {
        mobile: state.data.mobile,
      });
    }
  }

};

const getList = async () => {
  state.loadStatus = 'loading';
  const { code, data } = await assApi.user.list({
    page: state.page,
    list_rows: 10,
    platform: 'xyh',
    // category_id: state.category_id,
    // category_id: null,
    style: state.tabStyle,
    user_id: state.user_id,
  });

  if (code === 1) {
    state.total = data.total;
    // state.list = state.list.concat(data.data);
    setTimeout(() => {
      state.list = [...state.list, ...data.data];
    }, 100);
    if (state.list.length === 0) {
      state.loadStatus = 'noMore';
    }
    if (data.current_page < data.last_page) {
      state.loadStatus = 'more';
    } else {
      state.loadStatus = 'noMore';
    }
  }
};

const getData = async () => {
  const { code, data } = await assApi.user.details({
    id: state.user_id,
  });
  if (code === 1) {
    state.data = data;
    if (state.data.oneself === 1) {
      const data = sheep.$store('user').userInfo;
      state.userInfo = {
        avatar: data.avatar,
        nickname: data.nickname,
      }
    } else {
      state.userInfo = {
        avatar: state.data.avatar,
        nickname: state.data.nickname,
      }
    }
  }
};

const getCategory = async () => {
  const { code, data } = await assApi.user.categoryList();

  if (code === 1) {
    state.category = data;
    state.category_id = data[0].id;
    getList();
  }
};
</script>
<style lang="scss" scoped>
view {
  box-sizing: border-box;
}

.user-info {
  width: 100%;
  padding: 40rpx 26rpx 0;

  .user-info-avatar {
    width: 160rpx;
    height: 160rpx;
    border-radius: 50%;
    margin-right: 26rpx;
  }

  .user-info-text {
    flex: 1;
    height: 160rpx;
    padding-top: 26rpx;

    .user-info-name {
      .name {
        font-size: 36rpx;
        font-weight: normal;
        color: #ffffff;
      }

      .gender {
        min-width: 32rpx;
        min-height: 32rpx;
        width: 32rpx;
        height: 32rpx;
        margin-left: 10rpx;
      }
    }
  }
}

.synopsis {
  width: 100%;
  height: 136rpx;
  font-size: 32rpx;
  font-weight: normal;
  color: #ffffff;
  padding: 0 32rpx;
  margin-top: 20rpx;
}

.data-box {
  margin-top: 30rpx;
  width: 100%;
  padding: 0 24rpx;

  .data-left {
    width: 70%;
    margin-right: 40rpx;

    .data-left-item {
      flex: 1;

      .num {
        width: 100%;
        font-size: 30rpx;
        font-weight: normal;
        color: #ffffff;
        text-align: center;
      }

      .text {
        font-size: 28rpx;
        font-weight: normal;
        color: #ffffff;
        margin-top: 5rpx;
      }
    }
  }

  .data-right {
    flex: 1;

    .data-right-other {
      .data-right-other-care {
        width: 158rpx;
        height: 56rpx;
        border-radius: 30rpx;
        background: rgba(255, 255, 255, 0.5);
        font-size: 28rpx;
        font-weight: normal;
        line-height: 52rpx;
        text-align: center;
        color: #ffffff;
        margin-right: 20rpx;
        border: 2rpx solid #ffffff;
      }

      .data-right-other-chat {
        width: 158rpx;
        height: 56rpx;
        border-radius: 30rpx;
        background: rgba(255, 255, 255, 0.5);
        border: 2rpx solid #ffffff;

        image {
          width: 29rpx;
          height: 29rpx;
          margin-right: 12rpx;
        }

        view {
          font-size: 28rpx;
          font-weight: normal;
          color: #ffffff;
        }
      }
    }
  }
}

.data-right-my {
  width: 100%;
  .edit-user {
    width: 158rpx;
    height: 56rpx;
    border-radius: 30rpx;
    background: #48dfbd;
    font-size: 28rpx;
    font-weight: normal;
    line-height: 56rpx;
    text-align: center;
    color: #ffffff;
  }
}

.is-care {
  line-height: 56rpx !important;
  border: none !important;
  background-color: #48dfbd !important;
}

.tabs-box {
  width: 100%;
  height: 86rpx;
  background: #ffffff;
  border-bottom: 2rpx solid #fafafa;
  margin-top: 40rpx;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  padding: 0 232rpx;

  .tabs-item {
    font-size: 28rpx;
    font-weight: normal;
    color: #848282;
  }
}

.tab-active {
  color: #3d3d3d !important;
}

.category-box {
  width: 100%;
  height: 86rpx;
  background: #ffffff;
  padding-left: 20rpx;

  .category-item {
    width: 152rpx;
    height: 54rpx;
    border-radius: 30rpx;
    font-size: 28rpx;
    font-weight: normal;
    line-height: 54rpx;
    color: #848282;
    text-align: center;
  }
}

.category-active {
  color: #3d3d3d !important;
  background-color: #f6f6f6;
}

.list-box {
  width: 100%;
  background-color: #f5f5f5;
}
</style>